Template Matching using normalized correlation

Import Libraries


In [1]:
import numpy as np
import matplotlib.pyplot as plt
import skimage.feature as ski
import cv2

Read Image


In [2]:
image = cv2.imread('cars.jpg', cv2.IMREAD_GRAYSCALE)
car = image[300:550, 650:1300]
plt.figure(figsize=(15,12))
plt.subplot(1,2,1), plt.imshow(image, cmap='gray'), plt.title('Original Image')
plt.subplot(1,2,2), plt.imshow(car, cmap='gray'), plt.title('Car = Cropped image')
plt.show()


Detect Template


In [3]:
result = ski.match_template(image, car)
ij = np.unravel_index(np.argmax(result), result.shape)
x, y = ij[::-1]

Highlight matched region


In [4]:
hcar, wcar = car.shape
rect = plt.Rectangle((x, y), wcar, hcar, edgecolor='r', facecolor='none')

Show Detected region


In [5]:
fig = plt.figure(figsize=(20, 18))

plt.subplot(1, 3, 1), plt.imshow(car, cmap='gray'), plt.title('template')

ax2=plt.subplot(1, 3, 2, adjustable='box-forced')
plt.imshow(image, cmap='gray'), plt.title('image'), ax2.add_patch(rect)

plt.subplot(1, 3, 3), plt.imshow(result), plt.title('match_template \nresult'), plt.autoscale(False)
plt.plot(x, y, 'o', markeredgecolor='r', markerfacecolor='none', markersize=10)


Out[5]:
[<matplotlib.lines.Line2D at 0x7f9288532e80>]

In [6]:
plt.show()